package tankgame03;

import java.io.*;
import java.util.Vector;

/**
 * 该类用于记录相关信息，和文件交互
 */
public class Recorder {
	//定义变量，记录我方击毁敌人坦克数
	private static int allEnemyTanknum = 0;
	private static Vector<EnemyTank> enemyTanks = null;
	//定义一个Node的vector，用于保存的敌人的信息
	private static Vector<Node> nodes = new Vector<>();
	//定义IO对象，准备写数据到文件中
	private static FileWriter fw = null;
	private static FileReader fr = null;

	private static BufferedWriter bw = null;
	private static BufferedReader br = null;
	private static String recordFile = "/Users/yuuzy/Downloads/java/第十五章/chapter15/src/tankgame03/myRecord.txt";
	public static int getAllEnemyTanknum() {
		return allEnemyTanknum;
	}

	public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
		Recorder.enemyTanks = enemyTanks;
	}

	public static void setAllEnemyTanknum(int allEnemyTanknum) {
		Recorder.allEnemyTanknum = allEnemyTanknum;
	}
	//当我方坦克击毁一辆坦克，allEnemyTanknum++
	public static void addAllEnemyTanknum(){
		Recorder.allEnemyTanknum++;
	}

	public static String getRecordFile() {
		return recordFile;
	}

	//增加一个方法，用于读取recordFile，恢复相关信息
	public static Vector<Node> getNodesAndEnemyTankRec() throws IOException {
		fr = new FileReader(recordFile);
		br = new BufferedReader(fr);
		allEnemyTanknum = Integer.parseInt(br.readLine());
		//循环读取文件，生成nodes集合
		String line;
		while ((line = br.readLine()) != null){
			String[] lines = line.split(" ");
			Node node = new Node(Integer.parseInt(lines[0]), Integer.parseInt(lines[1]), Integer.parseInt(lines[2]));
			nodes.add(node);
		}
		if (br != null) {
			br.close();
		}
		return nodes;
	}
	//增加一个方法，当游戏退出时，我们将allEnemyTanknum,敌人坦克坐标保存到recordFile
	public static void keepRecord() throws IOException {
		fw = new FileWriter(recordFile);
		bw = new BufferedWriter(fw);
		bw.write(allEnemyTanknum + "\r\n");
		for (int i = 0; i < enemyTanks.size(); i++) {
			EnemyTank enemyTank = enemyTanks.get(i);
			if (enemyTank.isLive) {
				String record = enemyTank.getX() + " " + enemyTank.getY() + " " + enemyTank.getDirection();
				bw.write(record + "\r\n");
			}
		}
		bw.close();
	}
}
